﻿Imports System.Security.Cryptography
Imports System.Collections.Generic
Imports System.Data
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Xml
Imports System
Imports System.Windows.Forms


Public Class frmWebNet
    Public bNetWorkAvailable As Boolean = False
    Private StrCollection As New List(Of String) '与网络数据连接
    Private StrDatetime As New List(Of DateTime)
    Private mGetNettime As DateTime

    Private mConnectStr As String = "" '连接信息

    Public Urlstrs As New List(Of String) '软件下载地址
    Public mStr As String = "" '软件版本
    Private Sub frmWebNet_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Function GetNetWeb(ByVal Urlstrs As List(Of String), ByVal mStr As String) As Boolean
        mConnectStr = "正在查看本地网络状态..."
        Me.BackgroundWorker1.ReportProgress(1)
        If My.Computer.Network.IsAvailable = False Then
            mConnectStr = "本地网络不可用，请检查网络！"
            Me.BackgroundWorker1.ReportProgress(1)
            Return False
        End If

        mConnectStr = "本地网络状态正常！"
        Me.BackgroundWorker1.ReportProgress(1)


        ''获得网络程序的版本号
        'Dim LastVersion As String = ""
        'If GetTheLastUpdateVersion(mStr, LastVersion) = False Then '"http://www.eia65.com/UserManage/NAutoUpdater.xml"
        '    Return False
        'End If


        ''打开网络进行软件更新，并关闭已打开的程序
        ' ''获得本机程序的版本号  
        'Dim mVersion As String = Mid(My.Application.Info.Version.ToString, 1, 5)
        ''Dim Urlstrs As New List(Of String)
        ''Urlstrs.Add("http://www.eia65.com/index.php?option=com_product&lid=6&Itemid=28")
        ''Urlstrs.Add("http://www.era65.com/index.php?option=com_product&lid=6&Itemid=28")
        ''Urlstrs.Add("http://sjzwrj.vip4.eshimai.com/index.php?option=com_product&lid=6&Itemid=28")
        'If mVersion <> Mid(LastVersion, 1, 5) Then
        '    If LastVersion.Trim = "" Then
        '    Else
        '        If MsgBox("本程序已更新到 " & LastVersion & " 版本,请到 http://www.eia65.com 下载新版本程序,是否关闭本程序并进行下载更新!", MsgBoxStyle.YesNo, "提示") = MsgBoxResult.Yes Then
        '            Dim Req As WebRequest
        '            Dim Resp As WebResponse
        '            For i As Integer = 0 To Urlstrs.Count - 1
        '                Dim url As New Uri(Urlstrs.Item(i)) '定义一个URI
        '                Req = WebRequest.Create(url)
        '                '试探N个网站的连接
        '                Try
        '                    Resp = Req.GetResponse '获得一个响应
        '                    System.Diagnostics.Process.Start(Urlstrs.Item(i))
        '                    Exit For
        '                Catch ex As Exception
        '                End Try
        '            Next
        '            IsUpdateVersion = True
        '            Return IsUpdateVersion
        '        End If
        '    End If
        'End If


        '验证
        Dim mNetUrl As New List(Of String)
        mNetUrl.Add("http://www.eia65.com/UserManage/asUser.txt")
        mNetUrl.Add("http://www.era65.com/UserManage/asUser.txt")
        mNetUrl.Add("http://sjzwrj.vip4.eshimai.com/UserManage/asUser.txt")
        Dim mArryStr As New List(Of String)
        If GetStrReslut(mNetUrl, mArryStr) = False Then
            Return False
        End If
        '获得时间，及网络状态测试

        If GetInternetDateTime(mGetNettime) = False Then
            Return False
        End If

        If My.Computer.FileSystem.FileExists(My.Application.Info.DirectoryPath & "\asUser.txt") Then
            FileOpen(1, My.Application.Info.DirectoryPath & "\asUser.txt", OpenMode.Input)
            '读取文件信息
            Dim Str As String = ""
            Do Until EOF(1)
                Str = LineInput(1)
                If Str.Trim <> "" Then
                    Exit Do
                End If
            Loop
            FileClose(1)
            '验证数据
            Dim b As Boolean = False
            For i As Integer = 0 To mArryStr.Count - 1
                If Str = mArryStr.Item(i) Then
                    If mGetNettime >= StrDatetime.Item(i) Then
                        MsgBox("您的软件使用时间已到期,请与作者联系!", MsgBoxStyle.OkOnly, "提示")
                        Exit For
                    ElseIf StrDatetime.Item(i).Year - mGetNettime.Year = 0 And mGetNettime <= StrDatetime.Item(i) And StrDatetime.Item(i).Month - mGetNettime.Month = 0 And StrDatetime.Item(i).Day - mGetNettime.Day <= 7 Then
                        MsgBox("您的软件使用时间还有" & StrDatetime.Item(i).Day - mGetNettime.Day & "天,请与作者联系!", MsgBoxStyle.OkOnly, "提示")
                        b = True
                        Exit For
                    Else
                        b = True
                        Exit For
                    End If
                Else
                    b = False
                End If
            Next
            If b = True Then
                Return True
            Else
                '调用验证窗体
                Dim frma As New frmLogo
                frma.mArryS = StrCollection
                frma.mDatetime = StrDatetime
                frma.mNetTime = mGetNettime
                If frma.ShowDialog = Windows.Forms.DialogResult.OK Then

                Else
                    Return False
                End If
            End If
        Else
            '调用验证窗体
            Dim frma As New frmLogo
            frma.mArryS = StrCollection
            frma.mDatetime = StrDatetime
            frma.mNetTime = mGetNettime
            If frma.ShowDialog = Windows.Forms.DialogResult.OK Then

            Else
                Return False
            End If
        End If


        mConnectStr = "程序网络校验完成！"
        Me.BackgroundWorker1.ReportProgress(1)
        Return True

    End Function

    Public Function GetTheLastUpdateVersion(ByVal Urlstrs As String, ByRef LastVersion As String) As Boolean

        mConnectStr = "正在获取网络版本..."
        Me.BackgroundWorker1.ReportProgress(1)

        Try
            Dim url As New Uri(Urlstrs) '定义一个URI

            Dim Req As WebRequest
            Req = WebRequest.Create(url)
            Req.Timeout = 3000
            Dim Resp As WebResponse
            Resp = Req.GetResponse '获得一个响应

            '打开xml文件 
            Dim myReader As StreamReader = New StreamReader(Resp.GetResponseStream)
            Dim xml As XmlTextReader = New XmlTextReader(myReader)  'xml文件阅读器 
            While (xml.Read())
                If xml.Name = "Version" Then
                    '获取升级文档的最后一次更新版本
                    LastVersion = xml.GetAttribute("Num")
                    Exit While
                End If
            End While
            xml.Close()
            myReader.Close()

            mConnectStr = "获取网络版本成功！"
            Me.BackgroundWorker1.ReportProgress(1)
            Return True
        Catch ex As Exception
            mConnectStr = "获取网络版本失败，无法连接到主网络！" & "\n失败信息为：" & ex.Message
            Me.BackgroundWorker1.ReportProgress(1)
            Return False
        End Try
    End Function


    ''' <summary>
    ''' 获得Internet服务器日期时间
    ''' </summary>
    ''' <remarks></remarks>
    Public Function GetInternetDateTime(ByRef mNetTime As DateTime) As Boolean
        '内部网站时间
        If My.Computer.Network.IsAvailable = False Then
            Return False
        End If
        mConnectStr = "正在获取网络附加信息..."
        Me.BackgroundWorker1.ReportProgress(1)
        Dim Req As WebRequest
        Dim Str As String = ""
        Dim mArry As New List(Of String)
        Dim Resp As WebResponse

        Dim Urlstrs As New List(Of String)
        Urlstrs.Add("http://www.eia65.com/date.php")
        Urlstrs.Add("http://sjzwrj.vip4.eshimai.com/date.php")
        'Urlstrs.Add("http://www.era65.com/date.php")

        For i As Integer = 0 To Urlstrs.Count - 1
            Dim url As New Uri(Urlstrs.Item(i)) '定义一个URI
            Req = WebRequest.Create(url)
            '试探N个网站的连接
            Try
                Resp = Req.GetResponse '获得一个响应
                Exit For
            Catch ex As Exception
                mConnectStr = "获取网络信息第" & (i + 1).ToString & "失败！" & "失败信息为：" & ex.Message
                Me.BackgroundWorker1.ReportProgress(1)
                If i = 2 Then
                    Return False
                End If
            End Try
        Next
        Try
            Dim netStream As StreamReader
            netStream = New StreamReader(Resp.GetResponseStream)
            Str = netStream.ReadToEnd.ToString

            mConnectStr = "获取网络信息成功！"
            Me.BackgroundWorker1.ReportProgress(1)
            mNetTime = Str
            mConnectStr = "转化网络信息成功！"
            Me.BackgroundWorker1.ReportProgress(1)
            Return True
        Catch ex As Exception
            mConnectStr = "转化网络信息错误,请与相关人员联系！" & "错误信息为：" & ex.Message
            Me.BackgroundWorker1.ReportProgress(1)
            Return False
        End Try




        'mConnectStr = "正在获取网络附加信息..."
        'Me.BackgroundWorker1.ReportProgress(1)
        'Dim official, localtime As DateTime
        'Dim returndata As String = ""
        'Dim dates(4) As String
        'Dim times(4) As String
        'Dim tokens(11) As String

        'Dim mTimeZone(27) As String  'N个网络时间服务网址
        'mTimeZone(0) = "time-a.nist.gov"
        'mTimeZone(1) = "129.6.15.28"
        'mTimeZone(2) = "time-b.nist.gov"
        'mTimeZone(3) = "129.6.15.29"
        'mTimeZone(4) = "time-a.timefreq.bldrdoc.gov"
        'mTimeZone(5) = "132.163.4.101"
        'mTimeZone(6) = "time-b.timefreq.bldrdoc.gov"
        'mTimeZone(7) = "132.163.4.102"
        'mTimeZone(8) = "time-c.timefreq.bldrdoc.gov"
        'mTimeZone(9) = "132.163.4.103"
        'mTimeZone(10) = "utcnist.colorado.edu"
        'mTimeZone(11) = "128.138.140.44"
        'mTimeZone(12) = "time.nist.gov"
        'mTimeZone(13) = "192.43.244.18"
        'mTimeZone(14) = "time-nw.nist.gov"
        'mTimeZone(15) = "131.107.1.10"
        'mTimeZone(16) = "nist1.symmetricom.com"
        'mTimeZone(17) = "69.25.96.13"
        'mTimeZone(18) = "nist1-dc.glassey.com"
        'mTimeZone(19) = "216.200.93.8"
        'mTimeZone(20) = "nist1-ny.glassey.com"
        'mTimeZone(21) = "208.184.49.9"
        'mTimeZone(22) = "nist1-sj.glassey.com"
        'mTimeZone(23) = "207.126.98.204"
        'mTimeZone(24) = "nist1.aol-ca.truetime.com"
        'mTimeZone(25) = "207.200.81.113"
        'mTimeZone(26) = "nist1.aol-va.truetime.com"
        'mTimeZone(27) = "64.236.96.53"

        'Dim tcpclient As TcpClient = New TcpClient
        'tcpclient.ReceiveTimeout = 3000
        'For i As Integer = 0 To mTimeZone.Length - 1
        '    Try
        '        tcpclient.Connect(mTimeZone(i), 13)

        '        Dim NetworkStream As NetworkStream = tcpclient.GetStream()
        '        If NetworkStream.CanRead Then
        '            Dim bytes(tcpclient.ReceiveBufferSize) As Byte
        '            NetworkStream.Read(bytes, 0, tcpclient.ReceiveBufferSize)
        '            returndata = Encoding.ASCII.GetString(bytes)
        '        End If
        '        tcpclient.Close()
        '        '对获得的期日时间进行转化
        '        tokens = returndata.Split(" ") ' ')
        '        dates = tokens(1).Split("-")
        '        times = tokens(2).Split(":")
        '        official = New DateTime(Int32.Parse(dates(0)) + 2000, Int32.Parse(dates(1)), Int32.Parse(dates(2)), Int32.Parse(times(0)), Int32.Parse(times(1)), Int32.Parse(times(2)))
        '        localtime = TimeZone.CurrentTimeZone.ToLocalTime(official)
        '        mNetTime = localtime

        '        mConnectStr = "获取网络附加信息成功！"
        '        Me.BackgroundWorker1.ReportProgress(1)
        '        Return True
        '        Exit For
        '    Catch ex As Exception
        '        mConnectStr = "获取网络附加信息第" & (i + 1).ToString & "个主机失败,共" & mTimeZone.Length & "个主机" & "失败信息为：" & ex.Message
        '        Me.BackgroundWorker1.ReportProgress(1)
        '        If i = 27 Then

        '            Return False
        '        End If

        '    End Try
        'Next
        'Return False
    End Function



    ''' <summary>
    ''' 获得相应的网络数据
    ''' </summary>
    ''' <remarks></remarks>
    Public Function GetStrReslut(ByVal Urlstrs As List(Of String), ByRef NetInformationCode As List(Of String)) As Boolean
        mConnectStr = "正在获取网络信息..."
        Me.BackgroundWorker1.ReportProgress(1)
        Dim Req As WebRequest
        Dim Str As String = ""
        Dim mArry As New List(Of String)
        Dim Resp As WebResponse

        For i As Integer = 0 To Urlstrs.Count - 1
            Dim url As New Uri(Urlstrs.Item(i)) '定义一个URI

            Req = WebRequest.Create(url)
            Req.Timeout = 3000

            '试探N个网站的连接
            Try
                Resp = Req.GetResponse '获得一个响应

                Exit For
            Catch ex As Exception
                mConnectStr = "获取网络信息第" & (i + 1).ToString & "失败！" & "\n失败信息为：" & ex.Message
                Me.BackgroundWorker1.ReportProgress(1)
                If i = 2 Then
                    Return False
                End If
            End Try
        Next
        Try
            Dim netStream As StreamReader
            netStream = New StreamReader(Resp.GetResponseStream)
            Str = netStream.ReadToEnd.ToString

            mConnectStr = "获取网络信息成功！"
            Me.BackgroundWorker1.ReportProgress(1)
            For i As Integer = 0 To GetStringNumber(Str) / 5 - 1
                NetInformationCode.Add(GetString(Str, (i + 1) * 5).Trim)
                StrCollection.Add(NetInformationCode.Item(i))
                StrDatetime.Add(GetString(Str, (i + 1) * 5 - 1).Trim)
            Next
            mConnectStr = "转化网络信息成功！"
            Me.BackgroundWorker1.ReportProgress(1)
            Return True
        Catch ex As Exception
            mConnectStr = "转化网络信息错误,请与相关人员联系！" & "\n错误信息为：" & ex.Message
            Me.BackgroundWorker1.ReportProgress(1)
            Return False
        End Try
    End Function

    Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged

        Me.RichTextBox1.Text += mConnectStr & vbCrLf
    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        IsReadyForUse = GetNetWeb(Urlstrs, mStr)
    End Sub

    'Private Sub ButOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Me.DialogResult = Windows.Forms.DialogResult.OK
    'End Sub

    Private Sub ButCancal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButCancal.Click
        Me.DialogResult = Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub ButRese_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButRese.Click
        ButRese.Enabled = False

        If Me.BackgroundWorker1.IsBusy Then

            MessageBox.Show("网络程序仍在连接，请稍后。。。")
            Return
        End If


        Me.RichTextBox1.Clear()
        Me.BackgroundWorker1.RunWorkerAsync()
    End Sub

    '查看版本检查以及序列号等信息是否正确！
    Dim IsReadyForUse As Boolean = False


    Private IsUpdateVersion As Boolean = False '是否更新版本
    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted

        ButRese.Enabled = True
        If IsUpdateVersion Then
            Me.DialogResult = Windows.Forms.DialogResult.Cancel
            Me.Close()
        Else
            If IsReadyForUse Then
                Me.DialogResult = Windows.Forms.DialogResult.OK
                Me.Close()
            Else
                MessageBox.Show("网络校验失败，请检查网络后重试！")
            End If
        End If
    End Sub
End Class